package com.doubi.common.config.shiro;

import com.doubi.model.sys.TSysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;


/**
 * Created by IntelliJ IDEA.
 * User: MrDoubi
 * Date: 2019/1/10
 * Time: 17:22
 */
public class ShiroUtil {
    public static Subject getSubjct()
    {
        return SecurityUtils.getSubject();
    }

    public static Session getSession()
    {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout()
    {
        getSubjct().logout();
    }

    public static TSysUser getUser()
    {
        TSysUser user = new TSysUser();
        Subject subject = getSubjct();
        BeanUtils.copyProperties(subject.getPrincipal(),user);
        return user;
    }

    public static void setUser(TSysUser user)
    {
        Subject subject = getSubjct();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static String getUserId()
    {
        return getUser().getOid();
    }

    public static String getLoginName()
    {
        return getUser().getAccount();
    }

    public static String getIp()
    {
        return getSubjct().getSession().getHost();
    }

    public static String getSessionId()
    {
        return String.valueOf(getSubjct().getSession().getId());
    }
}
